const express = require('express');
const admin = express.Router();
const connection = require('../mysql/index');
const getNowFormatDate = require('../mysql/date');
const moment = require('moment');

// 退出登录
admin.get('/exit', (req, res) => {
  req.session.destroy(function (err) {
    if (err) {
      return res.render('admin/pub/delsession')
    }
    return res.redirect('/admin/login')
  })
})

// 登录页面
admin.get('/login', (req, res) => {
  return res.render('admin/login')
})
// 用户登录功能
admin.post('/login', (req, res) => {
  const { username, password } = req.body;
  if (username.trim().length < 4 || password.trim().length < 8) {
    return res.status(400).render('admin/error', { msg: '账号或密码输入错误' })
  }

  connection.query(`select * from user where Username = "${username}" or Password = "${password}"`, function (err, result) {

    if (err) {
      return res.render('admin/error', { msg: '服务器出现错误，请重新尝试' });
    } else if (result.length == 0) {
      return res.render('admin/error', { msg: '账号不存在或密码错误,请重新尝试' })
    } else {
      req.session.username = username
      req.session.role = result[0].role
      return res.redirect('/admin/user')
    }
  })

})


// 加载首页
admin.get('/user', (req, res) => {
  return res.render('admin/admin', {
    msg: req.session.username,
    role: req.session.role
  })
})


// 渲染新闻信息管理页面，包括列表
admin.get('/newsList', async (req, res) => {
  let pages = req.query.id || 1
  let count = 0;

  let arr = [];
  await connection.query(`select count(*) as count from news`, (err, resulf) => {
    count = resulf[0].count;
  })
  connection.query(`select id,Author,Createdata,Title from news limit ${(pages - 1) * 5}, 5`, function (err, resulf) {
    if (err) {
      return res.render('admin/CollegeNews/collegeNewsList', {
        msg: req.session.username,
        role: req.session.role,
        data: 'One'
      })
    } else {
      for (let i = 0; i < resulf.length; i++) {
        let obj = {};
        let arr1 = [];
        let arr2 = moment(resulf[i].Createdata).format('l').split('/').reverse();
        arr1[0] = arr2[0];
        arr1[1] = arr2[2];
        arr1[2] = arr2[1];
        obj['id'] = resulf[i].id;
        obj['Title'] = resulf[i].Title;
        obj['Createdata'] = arr1.join('-');
        obj['Author'] = resulf[i].Author;
        arr.push(obj);
      }


      return res.render('admin/CollegeNews/collegeNewsList', {
        msg: req.session.username,
        role: req.session.role,
        data: 'One',
        resulf: arr,
        page: Math.ceil(count / 5)
      })
    }
  })

})
// 添加新闻页面
admin.get('/user-add', (req, res) => {
  return res.render('admin/CollegeNews/addNews', {
    msg: req.session.username,
    role: req.session.role,
    data: 'One'
  })
})
// 添加新闻
admin.post('/useradd', (req, res) => {
  const { title, author, content } = req.body;

  function ac() {
    let sql = `insert into news values(null,'${author}','${content}','${getNowFormatDate()}','${title}')`;
    connection.query(sql, (err, result) => {
      return res.redirect('/admin/newsList');
    })
  }
  connection.query(`select Title from news where Title = '${title}'`, (err, resulf) => {
    if (resulf.length == 0) {
      return ac()
    } else {
      return res.render('admin/CollegeNews/error');
    }
  })


})
// 删除新闻
admin.post('/delete', (req, res) => {
  connection.query(`delete from news where id = ${req.body.id}`, function (err, resulf) {
    if (err) {
      console.log('新闻删除失败，请重新尝试')
    }
    return res.redirect('/admin/newsList')
  })
})
// 修改新闻
admin.get('/modify', (req, res) => {
  connection.query(`select * from news where id = ${req.query.id}`, (err, resulf) => {
    if (err) {
      return res.render('admin/CollegeNews/error2')
    }
    return res.render('admin/CollegeNews/modify', {
      datas: resulf[0],
      msg: req.session.username,
      role: req.session.role,
      data: 'One'
    })
  })

})
// 修改新闻
admin.post('/modify', (req, res) => {
  const { id, title, author, content } = req.body;
  connection.query(`update news set Title='${title}',Author = '${author}',Content='${content}' where id = ${id}`, (err, resuld) => {
    if (err) {
      return res.render('admin/CollegeNews/error2')
    }
    return res.redirect('/admin/newsList')
  })
})


// 校园公告列表
admin.get('/notice', async (req, res) => {
  let pages = req.query.id || 1
  let count = 0;

  let arr = [];
  await connection.query(`select count(*) as count from notice`, (err, resulf) => {
    count = resulf[0].count;
  })
  connection.query(`select id,Author,Createdata,Title from notice limit ${(pages - 1) * 5}, 5`, function (err, resulf) {
    if (err) {
      return res.render('admin/notice/noticeList', {
        msg: req.session.username,
        role: req.session.role,
        data: 'Tow',
        resulf: arr,
        page: Math.ceil(count / 5)
      })
    } else {
      for (let i = 0; i < resulf.length; i++) {
        let obj = {};
        let arr1 = [];
        let arr2 = moment(resulf[i].Createdata).format('l').split('/').reverse();
        arr1[0] = arr2[0];
        arr1[1] = arr2[2];
        arr1[2] = arr2[1];
        obj['id'] = resulf[i].id;
        obj['Title'] = resulf[i].Title;
        obj['Createdata'] = arr1.join('-');
        obj['Author'] = resulf[i].Author;
        arr.push(obj);
      }

      return res.render('admin/notice/noticeList', {
        msg: req.session.username,
        role: req.session.role,
        data: 'Tow',
        resulf: arr,
        page: Math.ceil(count / 5)
      })
    }
  })
})
// 添加公告
admin.get('/noticeAdd', (req, res) => {
  return res.render('admin/notice/noticeAdd', {
    msg: req.session.username,
    role: req.session.role,
    data: 'Tow'
  })
})
// 添加公告接口
admin.post('/noticeAdd', (req, res) => {
  const { title, author, content } = req.body;
  let sql = `insert into notice values(null,'${author}','${content}','${getNowFormatDate()}','${title}')`;
  connection.query(sql, (err, result) => {
  })
  return res.redirect('/admin/notice');
})
// 删除公告接口
admin.post('/noticeDel', (req, res) => {
  connection.query(`delete from notice where id = ${req.body.id}`, (err, resulf) => {
    return res.redirect('/admin/notice')
  })
})
// 修改公告列表
admin.get('/noticemodify', (req, res) => {
  connection.query(`select * from notice where id = ${req.query.id}`, (err, resulf) => {
    if (err) {
      return res.render('admin/notice/error2')
    }
    return res.render('admin/notice/noticemodify', {
      datas: resulf[0],
      msg: req.session.username,
      role: req.session.role,
      data: 'Tow'
    })
  })
})
// 修改公告列表 接口
admin.post('/noticemodify', (req, res) => {
  const { id, title, author, content } = req.body;
  connection.query(`update notice set Title='${title}',Author = '${author}',Content='${content}' where id = ${id}`, (err, resuld) => {
    if (err) {
      return res.render('admin/notice/error2')
    }
    return res.redirect('/admin/notice')
  })
})



// 友情链接列表
admin.get('/links', (req, res) => {
  let pages = req.query.id || 1;
  let count = 0;
  connection.query(`select count(*) from links`, (err, resulf) => {
    if (err) { } else { count = resulf[0].count }
  })

  connection.query(`select * from links limit ${(pages - 1) * 5}, 5`, (err, resulf) => {
    return res.render('admin/links/links', {
      msg: req.session.username,
      role: req.session.role,
      data: 'Three',
      resulf,
      page: Math.ceil(count / 5)
    });
  });


})
// 添加友情链接
admin.get('/linksadd', (req, res) => {
  return res.render('admin/links/linksadd', {
    msg: req.session.username,
    role: req.session.role,
    data: 'Three'
  })
})
// 添加友情链接
admin.post('/linksadd', (req, res) => {
  const { url, name, alt } = req.body;
  connection.query(`insert into links values(null,'${url}','${name}','${alt}')`, (err, resulf) => {
    if (err) {
      console.log('添加失败')
    }
    return res.redirect('/admin/links')
  })
})
// 删除友情链接
admin.post('/dellinks', (req, res) => {
  console.log(req.body)
  connection.query(`delete from links where id = ${req.body.id}`, (err, resilf) => {
    if (err) {
      console.log('删除失败')
    }
    return res.redirect('/admin/links');
  })
})



// 渲染用户列表
admin.get('/userlist', async (req, res) => {
  let pages = req.query.id || 1
  let count = 0;
  await connection.query(`select count(*) as count from user`, (err, resulf) => {
    count = resulf[0].count;
  })
  connection.query(`select id,Username,Email,role from user limit ${(pages - 1) * 5}, 5`, (err, resulf) => {
    if (err) {
      return res.render('admin/user/userlist', {
        msg: req.session.username,
        role: req.session.role,
        data: 'Five',
        resulf: [],
        count: 0
      })
    }
    return res.render('admin/user/userlist', {
      msg: req.session.username,
      role: req.session.role,
      data: 'Five',
      resulf,
      page: Math.ceil(count / 5)
    })
  })

})
// 删除用户
admin.post('/userdelete', (req, res) => {
  // console.log(req.body)
  const { id } = req.body
  connection.query(`delete from user where id = ${id}`, function (err, resulf) {
    if (err) {
      return res.redirect('/admin/user')
    }

    return res.redirect('/admin/userlist')
  });
})
// 添加用户页面
admin.get('/useradd', (req, res) => {
  return res.render('admin/user/useradd', {
    msg: req.session.username,
    role: req.session.role,
    data: 'Five'
  })
})
// 添加用户功能
admin.post('/adduse', (req, res) => {
  const { Username, Password, role, email } = req.body;
  function adduser() {
    connection.query(`insert into user values(null,'${Username}','${Password}','${email}','${role}')`, (err, resulf) => {
      if (err) {
        return res.render('admin/user/error', {
          msg: '服务器出错，请重新尝试'
        })
      }
      return res.redirect('/admin/userlist')
    })
  }
  connection.query(`select * from user where Username='${Username}' or Email = '${email}'`, (err, resulf) => {
    if (err) {
      return res.render('admin/user/error', {
        msg: '服务器出错，请重新尝试'
      })
    }
    if (resulf.length == 0) {
      adduser()
    } else {
      return res.render('admin/user/error', {
        msg: '昵称或邮箱已存在，请重新尝试'
      })
    }
  })

})
// 修改用户信息页面
admin.get('/usermodify', (req, res) => {
  connection.query(`select * from user where id = ${req.query.id}`, function (err, resulf) {
    if (err) {
      return res.redirect('/admin/userlist')
    }
    return res.render('admin/user/usermodify', {
      msg: req.session.username,
      role: req.session.role,
      data: 'Five',
      resulf: resulf[0]
    })
  })

})
// 修改用户信息
admin.post('/usermodify', (req, res) => {
  const { Username, Password, role, email, id } = req.body
  connection.query(`update user set Username = '${Username}',Password = '${Password}',role = '${role}',email = '${email}' where id = ${id}`, function (err, resulf) {
    if(err){
      return res.render('admin/user/error',{
        msg: '服务器出错，请重新尝试'
      })
    }
    return res.redirect('/admin/userlist')
  })
})

module.exports = admin